"use strict";

const Constant = require("../basics/constant");
const Result = require("../basics/result");
const DateUtil = require("../utils/time");
const BaseImpl = require("../basics/clz/baseimpl");
const KindModel = require("../model/kind");
const MaterialModel = require("../model/material");
const BottleBodyModel = require("../model/bottle_body");
const BottlePartsModel = require("../model/bottle_parts");
const CustomRecordModel = require("../model/custom_record");

/**
 * 通用服务
 */
class HomeImpl extends BaseImpl {

  /**
   * 类型列表
   */
  async findKindList() {
    return await KindModel.getInstant(this.cloud).selectList();
  }

  /**
   * 材质列表
   */
  async findMaterialList() {
    return await MaterialModel.getInstant(this.cloud).selectList();
  }


  /**
   * 配件列表
   */
  async findPartslList(params) {
    let { type } = params;
    if (type == 1) {
      return await BottleBodyModel.getInstant(this.cloud).selectList();
    } else {
      return await BottlePartsModel.getInstant(this.cloud).selectList(type);
    }
  }

  /**
   * 保存订单
   * @param {*} params 
   */
  async saveOrder(params) {
    let { itemId, skuId, deatils, openId } = params;
    if (!skuId) {
      skuId = "";
    }
    if (deatils.length == 0) {
      throw Result.error(Result.constant.paramfail, "请选择配件");
    }
    for (let i = 0; i < deatils.length; i++) {
      const { code, type } = deatils[i];
      let count = 0;
      if (type == 1) {
        count = await BottleBodyModel.getInstant(this.cloud).minus(code);
      } else {
        count = await BottlePartsModel.getInstant(this.cloud).minus(type, code);
      }
      if (count < 1) {
        throw Result.error(1000, "库存不足");
      }
    }
    let data = { itemId, skuId, deatils: JSON.stringify(deatils), openId, createtime: DateUtil.findStringTime() };
    await CustomRecordModel.getInstant(this.cloud).insertOne(data);
    return true;
  }

}

module.exports = HomeImpl;